<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>目录浏览 - xx-ai 文件浏览器</title>
    <link th:href="@{/css/bootstrap/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/bootstrap/font/bootstrap-icons.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
            <div class="container-fluid">
                <a class="navbar-brand" th:href="@{/file/}">
                    <i class="bi bi-folder2-open"></i>
                    xx-ai 文件浏览器
                </a>
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" th:href="@{/file/}">
                        <i class="bi bi-house"></i>
                        首页
                    </a>
                </div>
            </div>
        </nav>

        <!-- 错误信息显示 -->
        <div th:if="${error}" class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <span th:text="${error}"></span>
            <button type="button" class="btn-close" data-dismiss="alert"></button>
        </div>

        <!-- 目录浏览内容 -->
        <div th:if="${response != null and response.accessible}">
            <!-- 路径导航和控制面板 -->
            <div class="card mb-4">
                <div class="card-header">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h6 class="card-title mb-0">
                                <i class="bi bi-folder-open"></i>
                                当前目录
                            </h6>
                        </div>
                        <div class="col-md-6 text-end">
                            <!-- 操作按钮 -->
                            <div class="btn-group btn-group-sm me-2" role="group">
                                <a th:href="@{/file/upload(path=${currentPath})}" 
                                   class="btn btn-success">
                                    <i class="bi bi-cloud-upload"></i>
                                    上传文件
                                </a>
                                <button type="button" class="btn btn-outline-primary" 
                                        data-toggle="modal" data-target="#createDirModal">
                                    <i class="bi bi-folder-plus"></i>
                                    新建目录
                                </button>
                            </div>
                            
                            <!-- 视图切换按钮 -->
                            <div class="btn-group btn-group-sm me-2" role="group">
                                <button type="button" class="btn btn-outline-secondary" id="listViewBtn" onclick="switchView('list')">
                                    <i class="bi bi-list-ul"></i>
                                    列表
                                </button>
                                <button type="button" class="btn btn-outline-secondary" id="gridViewBtn" onclick="switchView('grid')">
                                    <i class="bi bi-grid-3x3"></i>
                                    图标
                                </button>
                            </div>
                            
                            <!-- 排序和显示选项 -->
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-secondary dropdown-toggle" 
                                        data-toggle="dropdown">
                                    <i class="bi bi-sort-down"></i>
                                    排序
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='name', sortOrder='asc', showHidden=${showHidden})}">
                                        <i class="bi bi-sort-alpha-down"></i> 名称 ↑
                                    </a></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='name', sortOrder='desc', showHidden=${showHidden})}">
                                        <i class="bi bi-sort-alpha-up"></i> 名称 ↓
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='size', sortOrder='asc', showHidden=${showHidden})}">
                                        <i class="bi bi-sort-numeric-down"></i> 大小 ↑
                                    </a></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='size', sortOrder='desc', showHidden=${showHidden})}">
                                        <i class="bi bi-sort-numeric-up"></i> 大小 ↓
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='lastModified', sortOrder='asc', showHidden=${showHidden})}">
                                        <i class="bi bi-calendar"></i> 修改时间 ↑
                                    </a></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='lastModified', sortOrder='desc', showHidden=${showHidden})}">
                                        <i class="bi bi-calendar"></i> 修改时间 ↓
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='created', sortOrder='asc', showHidden=${showHidden})}">
                                        <i class="bi bi-calendar-plus"></i> 创建时间 ↑
                                    </a></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, sortBy='created', sortOrder='desc', showHidden=${showHidden})}">
                                        <i class="bi bi-calendar-plus"></i> 创建时间 ↓
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" th:href="@{/file/browse(path=${currentPath}, showHidden=${showHidden})}">
                                        <i class="bi bi-x-circle"></i> 默认排序
                                    </a></li>
                                </ul>
                            </div>
                            <a th:href="@{/file/browse(path=${currentPath}, showHidden=${!showHidden}, sortBy=${sortBy}, sortOrder=${sortOrder})}" 
                               class="btn btn-outline-secondary btn-sm">
                                <i th:class="${showHidden} ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
                                <span th:text="${showHidden} ? '隐藏隐藏文件' : '显示隐藏文件'"></span>
                            </a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 面包屑导航 -->
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-3">
                            <li class="breadcrumb-item">
                                <a th:href="@{/file/}">
                                    <i class="bi bi-house"></i>
                                </a>
                            </li>
                            <li class="breadcrumb-item" th:if="${response.parentPath != null}">
                                <a th:href="@{/file/browse(path=${response.parentPath})}" 
                                   th:text="'上级目录'">
                                </a>
                            </li>
                            <li class="breadcrumb-item active" aria-current="page">
                                <span th:text="${response.currentPath}"></span>
                            </li>
                        </ol>
                    </nav>

                    <!-- 统计信息 -->
                    <div class="row text-center">
                        <div class="col-md-3">
                            <div class="bg-light p-2 rounded">
                                <strong th:text="${response.directoryCount}">0</strong>
                                <small class="text-muted d-block">目录</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="bg-light p-2 rounded">
                                <strong th:text="${response.fileCount}">0</strong>
                                <small class="text-muted d-block">文件</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="bg-light p-2 rounded">
                                <strong th:text="${fileService.formatFileSize(response.totalSize)}">0 B</strong>
                                <small class="text-muted d-block">总大小</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="bg-light p-2 rounded">
                                <strong th:text="${response.items != null ? response.items.size() : 0}">0</strong>
                                <small class="text-muted d-block">项目总数</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 调试信息（开发模式） -->
                    <div class="mt-3 p-2 bg-info bg-opacity-10 rounded small" th:if="${response.items != null}">
                        <i class="bi bi-info-circle"></i>
                        <strong>调试信息:</strong>
                        关页时间: <span id="loadTime"></span> |
                        图片文件数: <span id="imageCount">0</span> |
                        刷新次数: <span id="refreshCount">1</span>
                        <button type="button" class="btn btn-sm btn-outline-info ms-2" onclick="refreshDirectory()">
                            <i class="bi bi-arrow-clockwise"></i> 刷新检查
                        </button>
                    </div>
                </div>
            </div>

            <!-- 文件列表 -->
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="bi bi-list-ul" id="viewIcon"></i>
                        <span id="viewTitle">目录内容</span>
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div th:if="${response.items == null or response.items.empty}" class="text-center p-4">
                        <i class="bi bi-folder-x fs-1 text-muted"></i>
                        <p class="text-muted mt-2">此目录为空</p>
                    </div>
                    
                    <!-- 列表视图 -->
                    <div id="listView" class="table-responsive">
                        <div th:if="${response.items != null and !response.items.empty}">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th scope="col" style="width: 60px;"></th>
                                        <th scope="col">名称</th>
                                        <th scope="col" class="d-none d-md-table-cell">类型</th>
                                        <th scope="col" class="d-none d-md-table-cell">大小</th>
                                        <th scope="col" class="d-none d-lg-table-cell">修改时间</th>
                                        <th scope="col" class="d-none d-lg-table-cell">创建时间</th>
                                        <th scope="col" class="d-none d-lg-table-cell">权限</th>
                                        <th scope="col" style="width: 120px;">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 上级目录链接 -->
                                    <tr th:if="${response.parentPath != null}" class="table-info">
                                        <td>
                                            <i class="bi bi-arrow-up-circle text-primary"></i>
                                        </td>
                                        <td>
                                            <a th:href="@{/file/browse(path=${response.parentPath})}" 
                                               class="text-decoration-none fw-bold">
                                                .. (上级目录)
                                            </a>
                                        </td>
                                        <td class="d-none d-md-table-cell text-muted">目录</td>
                                        <td class="d-none d-md-table-cell text-muted">-</td>
                                        <td class="d-none d-lg-table-cell text-muted">-</td>
                                        <td class="d-none d-lg-table-cell text-muted">-</td>
                                        <td></td>
                                    </tr>

                                    <!-- 文件和目录列表 -->
                                    <tr th:each="item : ${response.items}" 
                                        th:class="${item.isDirectory} ? 'file-directory' : 'file-item'">
                                        <td>
                                            <!-- 目录图标 -->
                                            <div th:if="${item.isDirectory}" class="d-flex align-items-center">
                                                <i class="bi bi-folder-fill text-warning"></i>
                                            </div>
                                            <!-- 图片文件缩略图 -->
                                            <div th:if="${!item.isDirectory and fileService.isImageFile(item.path)}" class="d-flex align-items-center">
                                                <img th:src="@{/file/preview/thumbnail(path=${item.path}, width=48, height=48)}" 
                                                     class="thumbnail-small me-2" 
                                                     th:alt="${item.name}"
                                                     onerror="this.style.display='none'; this.nextElementSibling.style.display='inline';"
                                                     loading="lazy">
                                                <i class="bi bi-image text-success" style="display: none;"></i>
                                            </div>
                                            <!-- 视频文件图标 -->
                                            <div th:if="${!item.isDirectory and fileService.isVideoFile(item.path) and !fileService.isImageFile(item.path)}" class="d-flex align-items-center">
                                                <i class="bi bi-file-play text-primary"></i>
                                            </div>
                                            <!-- 其他文件图标 -->
                                            <div th:if="${!item.isDirectory and !fileService.isImageFile(item.path) and !fileService.isVideoFile(item.path)}">
                                                <i th:if="${fileService.isTextFile(item.path)}" class="bi bi-file-text text-info"></i>
                                                <i th:if="${!fileService.isTextFile(item.path)}" class="bi bi-file-earmark text-primary"></i>
                                            </div>
                                        </td>
                                        <td>
                                            <a th:if="${item.isDirectory}" 
                                               th:href="@{/file/browse(path=${item.path})}" 
                                               th:text="${item.name}"
                                               class="text-decoration-none fw-bold">
                                            </a>
                                            <!-- 图片文件显示特殊样式 -->
                                            <div th:if="${!item.isDirectory and fileService.isImageFile(item.path)}" class="d-flex align-items-center">
                                                <span th:text="${item.name}" 
                                                      class="file-name image-file-name small"
                                                      style="cursor: pointer;"
                                                      onclick="previewImageFromName(this)"
                                                      th:data-file-path="${item.path}"
                                                      th:data-file-name="${item.name}"
                                                      title="点击预览图片">
                                                </span>
                                            </div>
                                            <!-- 普通文件 -->
                                            <span th:if="${!item.isDirectory and !fileService.isImageFile(item.path)}" 
                                                  th:text="${item.name}"
                                                  class="file-name">
                                            </span>
                                        </td>
                                        <td class="d-none d-md-table-cell text-muted">
                                            <span th:if="${item.isDirectory}">目录</span>
                                            <span th:if="${!item.isDirectory and item.extension != null}" 
                                                  th:text="${item.extension}">
                                            </span>
                                            <span th:if="${!item.isDirectory and (item.extension == null or item.extension.empty)}">
                                                -
                                            </span>
                                        </td>
                                        <td class="d-none d-md-table-cell text-muted">
                                            <span th:if="${item.isDirectory}">-</span>
                                            <span th:if="${!item.isDirectory}" 
                                                  th:text="${fileService.formatFileSize(item.size)}">
                                            </span>
                                        </td>
                                        <td class="d-none d-lg-table-cell text-muted">
                                            <span th:text="${#temporals.format(item.lastModified, 'yyyy-MM-dd HH:mm:ss')}"></span>
                                        </td>
                                        <td class="d-none d-lg-table-cell text-muted">
                                            <span th:text="${#temporals.format(item.lastModified, 'yyyy-MM-dd HH:mm:ss')}"></span>
                                        </td>
                                        <td class="d-none d-lg-table-cell">
                                            <span th:if="${item.readable}" class="badge bg-success me-1">R</span>
                                            <span th:if="${item.writable}" class="badge bg-warning">W</span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <!-- 下载按钮（仅文件） -->
                                                <button th:if="${!item.isDirectory}" 
                                                        type="button"
                                                        class="btn btn-outline-primary btn-sm"
                                                        title="下载文件"
                                                        onclick="downloadFile(this)"
                                                        th:data-file-path="${item.path}">
                                                    <i class="bi bi-download"></i>
                                                </button>
                                                <!-- 图片预览按钮 -->
                                                <button th:if="${!item.isDirectory and fileService.isImageFile(item.path)}" 
                                                        type="button"
                                                        class="btn btn-outline-success btn-sm"
                                                        title="图片预览"
                                                        onclick="event.stopPropagation(); previewImage(this)"
                                                        th:data-file-path="${item.path}"
                                                        th:data-file-name="${item.name}">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <!-- 视频预览按钮 -->
                                                <button th:if="${!item.isDirectory and fileService.isVideoFile(item.path)}" 
                                                        type="button"
                                                        class="btn btn-outline-primary btn-sm"
                                                        title="视频预览"
                                                        onclick="event.stopPropagation(); previewVideo(this)"
                                                        th:data-file-path="${item.path}"
                                                        th:data-file-name="${item.name}">
                                                    <i class="bi bi-play-btn"></i>
                                                </button>
                                                <!-- 在线查看按钮（仅文本文件） -->
                                                <button th:if="${!item.isDirectory and fileService.isTextFile(item.path)}" 
                                                        type="button"
                                                        class="btn btn-outline-info btn-sm"
                                                        title="在线查看"
                                                        onclick="viewTextFileInline(this)"
                                                        th:data-file-path="${item.path}"
                                                        th:data-file-name="${item.name}">
                                                    <i class="bi bi-file-text"></i>
                                                </button>
                                                <!-- 删除按钮 -->
                                                <button type="button" 
                                                        class="btn btn-outline-danger btn-sm"
                                                        title="删除"
                                                        onclick="event.stopPropagation(); confirmDelete(this)" 
                                                        th:data-file-path="${item.path}"
                                                        th:data-file-name="${item.name}"
                                                        th:data-is-directory="${item.isDirectory}">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                                <!-- 重命名按钮 -->
                                                <button type="button" 
                                                        class="btn btn-outline-secondary btn-sm"
                                                        title="重命名"
                                                        onclick="event.stopPropagation(); showRenameModal(this)" 
                                                        th:data-file-path="${item.path}"
                                                        th:data-file-name="${item.name}">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- 网格视图 -->
                    <div id="gridView" class="d-none p-3">
                        <div th:if="${response.items != null and !response.items.empty}">
                            <!-- 上级目录链接 -->
                            <div th:if="${response.parentPath != null}" class="grid-item-container mb-3">
                                <div class="grid-item parent-dir" onclick="handleParentDirClick()">
                                    <div class="grid-item-icon">
                                        <i class="bi bi-arrow-up-circle fs-1 text-primary"></i>
                                    </div>
                                    <div class="grid-item-title">上级目录</div>
                                </div>
                            </div>
                            
                            <!-- 文件和目录网格 -->
                            <div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-6 g-3">
                                <div class="col" th:each="item : ${response.items}">
                                    <div class="grid-item" 
                                         th:data-path="${item.path}"
                                         th:data-name="${item.name}"
                                         th:data-is-directory="${item.isDirectory}"
                                         onclick="handleGridItemClick(this)"
                                         th:class="'grid-item ' + (${item.isDirectory} ? 'directory-item' : ('file-item' + (${fileService.isImageFile(item.path)} ? ' image-file' : (${fileService.isVideoFile(item.path)} ? ' video-file' : ''))))">
                                        <div class="grid-item-icon">
                                            <!-- 目录图标 -->
                                            <i th:if="${item.isDirectory}" class="bi bi-folder-fill fs-1 text-warning"></i>
                                            <!-- 图片文件缩略图 -->
                                            <div th:if="${!item.isDirectory and fileService.isImageFile(item.path)}" class="image-thumbnail-container">
                                                <img th:src="@{/file/preview/thumbnail(path=${item.path}, width=120, height=120)}" 
                                                     class="image-thumbnail" 
                                                     th:alt="${item.name}"
                                                     onerror="this.style.display='none'; this.nextElementSibling.style.display='block';"
                                                     loading="lazy">
                                                <i class="bi bi-image fs-1 text-success" style="display: none;"></i>
                                            </div>
                                            <!-- 视频文件图标 -->
                                            <i th:if="${!item.isDirectory and fileService.isVideoFile(item.path) and !fileService.isImageFile(item.path)}" class="bi bi-file-play fs-1 text-primary"></i>
                                            <!-- 文本文件图标 -->
                                            <i th:if="${!item.isDirectory and fileService.isTextFile(item.path) and !fileService.isImageFile(item.path) and !fileService.isVideoFile(item.path)}" class="bi bi-file-text fs-1 text-info"></i>
                                            <!-- 普通文件图标 -->
                                            <i th:if="${!item.isDirectory and !fileService.isImageFile(item.path) and !fileService.isTextFile(item.path) and !fileService.isVideoFile(item.path)}" class="bi bi-file-earmark fs-1 text-primary"></i>
                                        </div>
                                        <div class="grid-item-title" th:text="${item.name}"></div>
                                        <div class="grid-item-info">
                                            <small class="text-muted">
                                                <span th:if="${item.isDirectory}">目录</span>
                                                <span th:if="${!item.isDirectory}" th:text="${fileService.formatFileSize(item.size)}"></span>
                                            </small>
                                        </div>
                                        <!-- 操作按钮 -->
                                        <div class="grid-item-actions">
                                            <!-- 下载按钮（仅文件） -->
                                            <button th:if="${!item.isDirectory}" 
                                                    type="button"
                                                    class="btn btn-outline-primary btn-sm"
                                                    title="下载文件"
                                                    onclick="event.stopPropagation(); downloadFile(this)"
                                                    th:data-file-path="${item.path}">
                                                <i class="bi bi-download"></i>
                                            </button>
                                            <!-- 图片预览按钮 -->
                                            <button th:if="${!item.isDirectory and fileService.isImageFile(item.path)}" 
                                                    type="button"
                                                    class="btn btn-outline-success btn-sm"
                                                    title="图片预览"
                                                    onclick="event.stopPropagation(); previewImage(this)"
                                                    th:data-file-path="${item.path}"
                                                    th:data-file-name="${item.name}">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            <!-- 在线查看按钮（仅文本文件） -->
                                            <button th:if="${!item.isDirectory and fileService.isTextFile(item.path)}" 
                                                    type="button"
                                                    class="btn btn-outline-info btn-sm"
                                                    title="在线查看"
                                                    onclick="event.stopPropagation(); viewTextFileInline(this)"
                                                    th:data-file-path="${item.path}"
                                                    th:data-file-name="${item.name}">
                                                <i class="bi bi-file-text"></i>
                                            </button>
                                            <!-- 删除按钮 -->
                                            <button type="button" 
                                                    class="btn btn-outline-danger btn-sm"
                                                    title="删除"
                                                    onclick="event.stopPropagation(); confirmDelete(this)" 
                                                    th:data-file-path="${item.path}"
                                                    th:data-file-name="${item.name}"
                                                    th:data-is-directory="${item.isDirectory}">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 如果无法访问目录 -->
        <div th:if="${response != null and !response.accessible}" class="card">
            <div class="card-body text-center">
                <i class="bi bi-exclamation-triangle fs-1 text-warning"></i>
                <h5 class="mt-3">无法访问目录</h5>
                <p th:text="${response.errorMessage}" class="text-muted"></p>
                <a th:href="@{/file/}" class="btn btn-primary">
                    <i class="bi bi-house"></i>
                    返回首页
                </a>
            </div>
        </div>
    </div>

    <!-- 新建目录模态框 -->
    <div class="modal fade" id="createDirModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-folder-plus"></i>
                        新建目录
                    </h5>
                    <button type="button" class="btn-close" data-dismiss="modal"></button>
                </div>
                <form action="/file/mkdir" method="post">
                    <div class="modal-body">
                        <input type="hidden" name="parentPath" th:value="${currentPath}">
                        <div class="mb-3">
                            <label for="dirName" class="form-label">目录名称</label>
                            <input type="text" class="form-control" id="dirName" name="dirName" 
                                   placeholder="请输入目录名称" required>
                        </div>
                        <div class="form-text">
                            <i class="bi bi-info-circle"></i>
                            将在当前目录下创建新目录
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-folder-plus"></i>
                            创建
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">
                        <i class="bi bi-exclamation-triangle"></i>
                        确认删除
                    </h5>
                    <button type="button" class="btn-close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="deleteMessage">确定要删除这个文件吗？</p>
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle"></i>
                        <strong>警告：</strong>删除操作不可恢复！
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <form id="deleteForm" action="/file/delete" method="post" style="display: inline;">
                        <input type="hidden" id="deleteFilePath" name="filePath">
                        <button type="submit" class="btn btn-danger">
                            <i class="bi bi-trash"></i>
                            确认删除
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div class="modal fade" id="renameModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-pencil"></i>
                        重命名
                    </h5>
                    <button type="button" class="btn-close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="renameForm">
                        <input type="hidden" id="oldPath">
                        <div class="mb-3">
                            <label for="newName" class="form-label">新名称</label>
                            <input type="text" class="form-control" id="newName" name="newName" 
                                   placeholder="请输入新名称" required>
                        </div>
                        <div class="form-text">
                            <i class="bi bi-info-circle"></i>
                            请输入新的文件或目录名称
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="renameSubmitBtn">
                        <i class="bi bi-pencil"></i>
                        确认重命名
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div class="modal fade" id="imagePreviewModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-image"></i>
                        <span id="imagePreviewTitle">图片预览</span>
                    </h5>
                    <button type="button" class="btn-close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center position-relative">
                    <!-- 左切换按钮 -->
                    <button type="button" id="prevImageBtn" class="btn btn-outline-primary position-absolute d-none" style="left: 10px; top: 50%; transform: translateY(-50%); z-index: 10;">
                        <i class="bi bi-chevron-left"></i>
                    </button>
                    
                    <!-- 右切换按钮 -->
                    <button type="button" id="nextImageBtn" class="btn btn-outline-primary position-absolute d-none" style="right: 10px; top: 50%; transform: translateY(-50%); z-index: 10;">
                        <i class="bi bi-chevron-right"></i>
                    </button>
                    
                    <!-- 加载提示 -->
                    <div id="imageLoadingSpinner" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">正在加载图片...</p>
                    </div>
                    
                    <!-- 图片容器 -->
                    <div id="imageContainer" class="d-none">
                        <img id="previewImage" 
                             class="img-fluid rounded shadow" 
                             style="max-height: 70vh; max-width: 100%;"
                             alt="图片预览">
                    </div>
                    
                    <!-- 错误信息 -->
                    <div id="imageError" class="d-none text-center py-5">
                        <i class="bi bi-exclamation-triangle fs-1 text-warning"></i>
                        <p class="mt-2 text-muted">无法加载图片</p>
                    </div>
                    
                    <!-- 图片信息 -->
                    <div id="imageInfo" class="mt-3 d-none">
                        <div class="row text-start">
                            <div class="col-md-6">
                                <small class="text-muted">
                                    <strong>文件名：</strong> <span id="imageFileName"></span><br>
                                    <strong>文件大小：</strong> <span id="imageFileSize"></span><br>
                                    <strong>文件类型：</strong> <span id="imageFileType"></span>
                                </small>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">
                                    <strong>图片尺寸：</strong> <span id="imageDimensions"></span><br>
                                    <strong>修改时间：</strong> <span id="imageLastModified"></span>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="bi bi-x"></i>
                        关闭
                    </button>
                    <button type="button" id="downloadImageBtn" class="btn btn-primary">
                        <i class="bi bi-download"></i>
                        下载原图
                    </button>
                    <button type="button" id="openImageBtn" class="btn btn-outline-primary">
                        <i class="bi bi-box-arrow-up-right"></i>
                        在新窗口打开
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 视频预览模态框 -->
    <div class="modal fade" id="videoPreviewModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-play-btn"></i>
                        <span id="videoPreviewTitle">视频预览</span>
                    </h5>
                    <button type="button" class="btn-close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <!-- 视频容器 -->
                    <div id="videoContainer">
                        <video id="previewVideo" 
                               class="img-fluid rounded shadow" 
                               style="max-height: 70vh; max-width: 100%;"
                               controls
                               preload="metadata">
                            您的浏览器不支持视频播放。
                        </video>
                    </div>
                    
                    <!-- 视频信息 -->
                    <div id="videoInfo" class="mt-3">
                        <div class="row text-start">
                            <div class="col-md-6">
                                <small class="text-muted">
                                    <strong>文件名：</strong> <span id="videoFileName"></span><br>
                                    <strong>文件大小：</strong> <span id="videoFileSize"></span><br>
                                    <strong>文件类型：</strong> <span id="videoFileType"></span>
                                </small>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">
                                    <strong>修改时间：</strong> <span id="videoLastModified"></span>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="bi bi-x"></i>
                        关闭
                    </button>
                    <button type="button" id="downloadVideoBtn" class="btn btn-primary">
                        <i class="bi bi-download"></i>
                        下载视频
                    </button>
                    <button type="button" id="openVideoBtn" class="btn btn-outline-primary">
                        <i class="bi bi-box-arrow-up-right"></i>
                        在新窗口打开
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/jquery-3.6.0.min.js}"></script>
    <script th:src="@{/js/bootstrap/bootstrap.bundle.min.js}"></script>
    <script th:src="@{/js/app.js}"></script>
    <script>
        // 视图切换功能
        function switchView(viewType) {
            try {
                const listView = $('#listView');
                const gridView = $('#gridView');
                const listViewBtn = $('#listViewBtn');
                const gridViewBtn = $('#gridViewBtn');
                const viewIcon = $('#viewIcon');
                const viewTitle = $('#viewTitle');
                
                // 检查必要的元素是否存在
                if (listView.length === 0 || gridView.length === 0) {
                    console.error('视图容器元素未找到:', { listView: listView.length > 0, gridView: gridView.length > 0 });
                    return;
                }
                
                if (listViewBtn.length === 0 || gridViewBtn.length === 0) {
                    console.error('视图切换按钮未找到:', { listViewBtn: listViewBtn.length > 0, gridViewBtn: gridViewBtn.length > 0 });
                    return;
                }
                
                console.log('切换视图类型:', viewType);
                
                if (viewType === 'list') {
                    // 显示列表视图
                    listView.removeClass('d-none');
                    gridView.addClass('d-none');
                    
                    // 更新按钮状态
                    listViewBtn.addClass('active').removeClass('btn-outline-secondary').addClass('btn-secondary');
                    gridViewBtn.removeClass('active btn-secondary').addClass('btn-outline-secondary');
                    
                    // 更新标题和图标
                    if (viewIcon.length > 0) viewIcon.attr('class', 'bi bi-list-ul');
                    if (viewTitle.length > 0) viewTitle.text('目录内容 - 列表视图');
                    
                } else if (viewType === 'grid') {
                    // 显示网格视图
                    listView.addClass('d-none');
                    gridView.removeClass('d-none');
                    
                    // 更新按钮状态
                    gridViewBtn.addClass('active').removeClass('btn-outline-secondary').addClass('btn-secondary');
                    listViewBtn.removeClass('active btn-secondary').addClass('btn-outline-secondary');
                    
                    // 更新标题和图标
                    if (viewIcon.length > 0) viewIcon.attr('class', 'bi bi-grid-3x3');
                    if (viewTitle.length > 0) viewTitle.text('目录内容 - 图标视图');
                }
                
                // 保存用户偏好到本地存储
                try {
                    localStorage.setItem('fileViewType', viewType);
                    console.log('用户偏好已保存:', viewType);
                } catch (e) {
                    console.warn('无法保存视图偏好设置:', e);
                }
                
            } catch (error) {
                console.error('视图切换函数执行错误:', error);
            }
        }
        
        // 立即将所有onclick事件使用的函数暴露到全局作用域，确保onclick事件能够访问
        window.switchView = switchView;
        window.refreshDirectory = refreshDirectory;
        window.previewImageFromName = previewImageFromName;
        window.previewImage = previewImage;
        window.viewTextFileInline = viewTextFileInline;
        window.confirmDelete = confirmDelete;
        window.getParentDirUrl = getParentDirUrl;
        window.handleGridItemClick = handleGridItemClick;
        window.downloadFile = downloadFile;
        window.showCreateDirectoryModal = showCreateDirectoryModal;
        window.handleParentDirClick = handleParentDirClick;
        
        // 处理网格项点击事件
        function handleGridItemClick(element) {
            const path = $(element).attr('data-path');
            const name = $(element).attr('data-name');
            const isDirectory = $(element).attr('data-is-directory') === 'true';
            
            if (isDirectory) {
                navigateToDirectory(path);
            } else {
                handleFileClick(path, name);
            }
        }
        
        // 缩略图加载处理
        function handleThumbnailLoad() {
            // 为所有缩略图添加加载事件
            $('.image-thumbnail').each(function() {
                const container = $(this).closest('.image-thumbnail-container');
                if (container.length > 0) {
                    // 显示加载动画
                    container.addClass('loading');
                    
                    // 图片加载成功
                    $(this).on('load', function() {
                        container.removeClass('loading');
                    });
                    
                    // 图片加载失败
                    $(this).on('error', function() {
                        container.removeClass('loading');
                        // 错误处理已在HTML中定义
                    });
                }
            });
            
            // 为小缩略图添加错误处理
            $('.thumbnail-small').each(function() {
                $(this).on('error', function() {
                    // 错误处理已在HTML中定义
                });
            });
        }
        
        // 懒加载支持检测
        function initLazyLoading() {
            if ('IntersectionObserver' in window) {
                const imageObserver = new IntersectionObserver((entries, observer) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            if (img.dataset.src) {
                                img.src = img.dataset.src;
                                img.removeAttribute('data-src');
                                observer.unobserve(img);
                            }
                        }
                    });
                });
                
                // 观察所有懒加载图片
                $('img[data-src]').each(function() {
                    imageObserver.observe(this);
                });
            }
        }
        
        // 网格视图交互函数
        function navigateToDirectory(path) {
            try {
                window.location.href = `/file/browse?path=${encodeURIComponent(path)}`;
            } catch (e) {
                console.error('导航到目录失败:', e);
            }
        }
        
        function handleFileClick(path, name) {
            try {
                // 对于图片文件，直接预览
                if (isImageFile(path)) {
                    const tempButton = {
                        getAttribute: function(attr) {
                            if (attr === 'data-file-path') return path;
                            if (attr === 'data-file-name') return name;
                            return null;
                        }
                    };
                    previewImage(tempButton);
                }
                // 对于视频文件，直接预览
                else if (isVideoFile(path)) {
                    const tempButton = {
                        getAttribute: function(attr) {
                            if (attr === 'data-file-path') return path;
                            if (attr === 'data-file-name') return name;
                            return null;
                        }
                    };
                    previewVideo(tempButton);
                }
                // 对于其他文件，可以根据文件类型进行不同处理
                // 这里暂时不做处理，用户可以通过操作按钮进行操作
            } catch (e) {
                console.error('处理文件点击失败:', e);
            }
        }
        
        function handleGridItemClick(element) {
            try {
                const path = $(element).attr('data-path');
                const name = $(element).attr('data-name');
                const isDirectory = $(element).attr('data-is-directory') === 'true';
                
                if (isDirectory) {
                    navigateToDirectory(path);
                } else {
                    handleFileClick(path, name);
                }
            } catch (e) {
                console.error('处理网格项点击失败:', e);
            }
        }
                
        // 检查是否为图片文件
        function isImageFile(filePath) {
            if (!filePath) return false;
            const extension = filePath.split('.').pop().toLowerCase();
            const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'];
            return imageExtensions.includes(extension);
        }
        
        // 检查是否为视频文件
        function isVideoFile(filePath) {
            if (!filePath) return false;
            const extension = filePath.split('.').pop().toLowerCase();
            const videoExtensions = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'];
            return videoExtensions.includes(extension);
        }
        
        // 视频预览函数
        function previewVideo(button) {
            try {
                const filePath = $(button).attr('data-file-path');
                const fileName = $(button).attr('data-file-name');
                
                if (!filePath || !fileName) {
                    console.error('缺少必要的文件信息');
                    return;
                }
                
                // 保存当前视频信息到全局变量
                window.currentVideo = {
                    path: filePath,
                    name: fileName
                };
                
                // 设置模态框标题
                const titleElement = $('#videoPreviewTitle');
                if (titleElement.length > 0) {
                    titleElement.text(`视频预览 - ${fileName}`);
                }
                
                // 设置下载和打开链接
                const downloadUrl = `/file/download?path=${encodeURIComponent(filePath)}`;
                const previewUrl = `/file/preview/video?path=${encodeURIComponent(filePath)}`;
                
                // 为按钮设置点击事件
                const downloadBtn = $('#downloadVideoBtn');
                const openBtn = $('#openVideoBtn');
                
                if (downloadBtn.length > 0) {
                    downloadBtn.off('click').on('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // 使用隐藏的a标签进行下载
                        const link = $('<a>').attr('href', downloadUrl).css('display', 'none').attr('download', '');
                        $('body').append(link);
                        link[0].click();
                        link.remove();
                        
                        console.log('从视频预览下载文件:', filePath);
                    });
                }
                
                if (openBtn.length > 0) {
                    openBtn.off('click').on('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        window.open(previewUrl, '_blank');
                    });
                }
                
                // 设置视频源
                const videoElement = $('#previewVideo');
                if (videoElement.length > 0) {
                    videoElement.attr('src', previewUrl);
                }
                
                // 显示模态框
                const modalElement = $('#videoPreviewModal');
                if (modalElement.length > 0) {
                    // Bootstrap 4 语法
                    $('#videoPreviewModal').modal('show');
                } else {
                    console.error('找不到视频预览模态框');
                }
            } catch (e) {
                console.error('视频预览函数执行失败:', e);
                alert('视频预览失败，请稍后重试');
            }
        }
        
        // 暴露到全局作用域
        window.previewVideo = previewVideo;
        
        function downloadFile(button) {
            try {
                const filePath = $(button).attr('data-file-path');
                
                if (!filePath) {
                    console.error('缺少文件路径信息');
                    alert('缺少文件路径信息');
                    return;
                }
                
                // 显示下载状态
                const $button = $(button);
                const originalHtml = $button.html();
                $button.html('<i class="bi bi-download"></i> 下载中...');
                $button.prop('disabled', true);
                
                // 使用隐藏的a标签进行下载，避免直接修改window.location
                const downloadUrl = `/file/download?path=${encodeURIComponent(filePath)}`;
                const link = $('<a>').attr('href', downloadUrl).css('display', 'none').attr('download', '');
                $('body').append(link);
                link[0].click();
                link.remove();
                
                console.log('开始下载文件:', filePath);
                
                // 恢复按钮状态
                setTimeout(() => {
                    $button.html(originalHtml);
                    $button.prop('disabled', false);
                }, 2000);
                
            } catch (e) {
                console.error('下载文件失败:', e);
                alert('下载文件失败: ' + e.message);
                
                // 发生错误时也要恢复按钮状态
                const $button = $(button);
                $button.html('<i class="bi bi-download"></i>');
                $button.prop('disabled', false);
            }
        }
        
        function viewTextFileInline(button) {
            try {
                const filePath = $(button).attr('data-file-path');
                const fileName = $(button).attr('data-file-name');
                
                if (!filePath) {
                    console.error('缺少文件路径信息');
                    return;
                }
                
                // 在新窗口中打开文本文件，使用inline模式
                const url = `/file/download?path=${encodeURIComponent(filePath)}&inline=true`;
                const newWindow = window.open(url, '_blank');
                
                // 检查是否成功打开新窗口
                if (!newWindow) {
                    alert('无法打开新窗口，请检查浏览器弹窗阻止设置');
                }
            } catch (e) {
                console.error('打开文本文件失败:', e);
                alert('打开文本文件失败');
            }
        }
        
        // 请求刷新目录函数名称统一
        function getParentDirUrl() {
            try {
                // 使用 Thymeleaf 的 JavaScript 内联语法，安全处理路径
                const parentPath = /*[[${response.parentPath}]]*/ null;
                console.log('原始 parentPath:', parentPath);
                
                if (!parentPath || parentPath === null || parentPath === 'null') {
                    console.log('parentPath 为空，返回根目录');
                    return '/file/';
                }
                
                const encodedPath = encodeURIComponent(parentPath);
                const url = `/file/browse?path=${encodedPath}`;
                console.log('生成的URL:', url);
                
                return url;
            } catch (e) {
                console.error('获取父目录URL失败:', e);
                return '/file/';
            }
        }
        
        // 处理上级目录点击事件
        function handleParentDirClick() {
            try {
                const url = getParentDirUrl();
                window.location.href = url;
            } catch (e) {
                console.error('导航到上级目录失败:', e);
                // 备用方案：直接回到根目录
                window.location.href = '/file/';
            }
        }
        
        // 初始化视图类型
        function initializeView() {
            try {
                console.log('开始初始化视图...');
                
                // 检查元素是否存在
                const listView = $('#listView');
                const gridView = $('#gridView');
                const listViewBtn = $('#listViewBtn');
                const gridViewBtn = $('#gridViewBtn');
                
                console.log('元素检查:', {
                    listView: listView.length > 0,
                    gridView: gridView.length > 0,
                    listViewBtn: listViewBtn.length > 0,
                    gridViewBtn: gridViewBtn.length > 0
                });
                
                if (listView.length === 0 || gridView.length === 0 || listViewBtn.length === 0 || gridViewBtn.length === 0) {
                    console.error('关键元素缺失，无法初始化视图切换功能');
                    return;
                }
                
                // 从本地存储获取用户偏好
                const savedViewType = localStorage.getItem('fileViewType') || 'list';
                console.log('初始化视图类型:', savedViewType);
                
                // 调用视图切换函数
                switchView(savedViewType);
                
                // 初始化调试信息
                initializeDebugInfo();
                
                console.log('视图初始化完成');
                
            } catch (e) {
                console.error('初始化视图失败:', e);
                // 默认使用列表视图
                try {
                    switchView('list');
                } catch (fallbackError) {
                    console.error('退回初始化也失败:', fallbackError);
                }
            }
        }
        
        // 初始化调试信息
        function initializeDebugInfo() {
            try {
                // 设置加载时间
                const loadTimeElement = $('#loadTime');
                if (loadTimeElement.length > 0) {
                    loadTimeElement.text(new Date().toLocaleTimeString());
                }
                
                // 统计图片数量
                updateImageCount();
                
                // 设置刷新次数
                const refreshCount = parseInt(sessionStorage.getItem('refreshCount') || '0') + 1;
                sessionStorage.setItem('refreshCount', refreshCount.toString());
                const refreshCountElement = $('#refreshCount');
                if (refreshCountElement.length > 0) {
                    refreshCountElement.text(refreshCount);
                }
                
                console.log('调试信息初始化完成');
            } catch (e) {
                console.error('初始化调试信息失败:', e);
            }
        }
        
        // 更新图片数量统计
        function updateImageCount() {
            try {
                let imageCount = 0;
                
                // 通过DOM元素统计图片数量
                $('[data-file-path]').each(function() {
                    const filePath = $(this).attr('data-file-path');
                    if (filePath && isImageFile(filePath)) {
                        imageCount++;
                    }
                });
                
                // 更新显示
                const imageCountElement = $('#imageCount');
                if (imageCountElement.length > 0) {
                    imageCountElement.text(imageCount);
                }
                
                console.log('图片数量统计:', {
                    totalImageFiles: imageCount
                });
                
                return imageCount;
            } catch (e) {
                console.error('统计图片数量失败:', e);
                return 0;
            }
        }
        
        // 刷新目录函数
        function refreshDirectory() {
            try {
                console.log('手动刷新目录...');
                
                // 显示加载状态
                const refreshBtn = $(event.target).closest('button');
                const originalHtml = refreshBtn.html();
                refreshBtn.html('<i class="bi bi-arrow-clockwise spinner-border spinner-border-sm"></i> 刷新中...');
                refreshBtn.prop('disabled', true);
                
                // 重新加载页面
                setTimeout(() => {
                    window.location.reload();
                }, 500);
                
            } catch (e) {
                console.error('刷新目录失败:', e);
            }
        }
        
        // 暴露到全局作用域
        window.refreshDirectory = refreshDirectory;
        
        // 从文件名点击预览图片
        function previewImageFromName(element) {
            const filePath = $(element).attr('data-file-path');
            const fileName = $(element).attr('data-file-name');
            
            // 保存当前图片信息到全局变量
            window.currentImage = {
                path: filePath,
                name: fileName,
                element: element  // 保存元素引用用于导航
            };
            
            // 创建一个临时按钮对象来复用现有的预览功能
            const tempButton = {
                getAttribute: function(attr) {
                    if (attr === 'data-file-path') return filePath;
                    if (attr === 'data-file-name') return fileName;
                    return null;
                }
            };
            
            // 调用现有的图片预览功能
            previewImage(tempButton);
        }
        
        // 暴露到全局作用域
        window.previewImageFromName = previewImageFromName;
        
        // 图片预览函数
        function previewImage(button) {
            try {
                const filePath = $(button).attr('data-file-path');
                const fileName = $(button).attr('data-file-name');
                
                if (!filePath || !fileName) {
                    console.error('缺少必要的文件信息');
                    return;
                }
                
                // 保存当前图片信息到全局变量
                window.currentImage = {
                    path: filePath,
                    name: fileName
                };
                
                // 设置模态框标题
                const titleElement = $('#imagePreviewTitle');
                if (titleElement.length > 0) {
                    titleElement.text(`图片预览 - ${fileName}`);
                }
                
                // 设置下载和打开链接（但不会自动触发）
                const downloadUrl = `/file/download?path=${encodeURIComponent(filePath)}`;
                const previewUrl = `/file/preview/image?path=${encodeURIComponent(filePath)}`;
                
                // 为按钮设置点击事件，而不是直接设置href
                const downloadBtn = $('#downloadImageBtn');
                const openBtn = $('#openImageBtn');
                
                if (downloadBtn.length > 0) {
                    downloadBtn.off('click').on('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // 使用隐藏的a标签进行下载
                        const link = $('<a>').attr('href', downloadUrl).css('display', 'none').attr('download', '');
                        $('body').append(link);
                        link[0].click();
                        link.remove();
                        
                        console.log('从图片预览下载文件:', filePath);
                    });
                }
                
                if (openBtn.length > 0) {
                    openBtn.off('click').on('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        window.open(previewUrl, '_blank');
                    });
                }
                
                // 显示模态框
                const modalElement = $('#imagePreviewModal');
                if (modalElement.length > 0) {
                    // Bootstrap 4 语法
                    $('#imagePreviewModal').modal('show');
                    
                    // 重置状态
                    resetImagePreviewState();
                    
                    // 加载图片
                    loadImagePreview(filePath, fileName);
                    
                    // 更新切换按钮状态
                    updateNavigationButtons();
                } else {
                    console.error('找不到图片预览模态框');
                }
            } catch (e) {
                console.error('图片预览函数执行失败:', e);
                alert('图片预览失败，请稍后重试');
            }
        }
        
        // 暴露到全局作用域
        window.previewImage = previewImage;
        
        // 重置图片预览状态
        function resetImagePreviewState() {
            $('#imageLoadingSpinner').removeClass('d-none');
            $('#imageContainer').addClass('d-none');
            $('#imageError').addClass('d-none');
            $('#imageInfo').addClass('d-none');
        }
        
        // 加载图片预览
        function loadImagePreview(filePath, fileName) {
            const previewImage = $('#previewImage');
            const imageUrl = `/file/preview/image?path=${encodeURIComponent(filePath)}`;
            
            // 加载图片
            previewImage.off('load').on('load', function() {
                $('#imageLoadingSpinner').addClass('d-none');
                $('#imageContainer').removeClass('d-none');
                
                // 加载图片信息
                loadImageInfo(filePath);
            });
            
            previewImage.off('error').on('error', function() {
                $('#imageLoadingSpinner').addClass('d-none');
                $('#imageError').removeClass('d-none');
            });
            
            previewImage.attr('src', imageUrl);
        }
        
        // 加载图片信息
        function loadImageInfo(filePath) {
            fetch(`/file/api/image-info?path=${encodeURIComponent(filePath)}`)
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    }
                    throw new Error('获取图片信息失败');
                })
                .then(imageInfo => {
                    // 显示图片信息
                    $('#imageFileName').text(imageInfo.name || '未知');
                    $('#imageFileSize').text(formatFileSize(imageInfo.size || 0));
                    $('#imageFileType').text(imageInfo.extension || '未知');
                    
                    if (imageInfo.width && imageInfo.height) {
                        $('#imageDimensions').text(`${imageInfo.width} x ${imageInfo.height} 像素`);
                    } else {
                        $('#imageDimensions').text('未知');
                    }
                    
                    if (imageInfo.lastModified) {
                        const date = new Date(imageInfo.lastModified);
                        $('#imageLastModified').text(date.toLocaleString('zh-CN'));
                    } else {
                        $('#imageLastModified').text('未知');
                    }
                    
                    $('#imageInfo').removeClass('d-none');
                })
                .catch(error => {
                    console.error('加载图片信息失败:', error);
                    // 不显示错误，只是不显示信息
                });
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }
        
        // 获取当前目录中的所有图片文件
        function getImageFilesInCurrentDirectory() {
            const imageFiles = [];
            $('.image-file-name[data-file-path]').each(function() {
                const filePath = $(this).attr('data-file-path');
                const fileName = $(this).attr('data-file-name');
                if (filePath && fileName) {
                    imageFiles.push({
                        path: filePath,
                        name: fileName,
                        element: this
                    });
                }
            });
            return imageFiles;
        }
        
        // 查找当前图片在图片列表中的索引
        function getCurrentImageIndex(imageFiles) {
            if (!window.currentImage || !window.currentImage.path) return -1;
            
            for (let i = 0; i < imageFiles.length; i++) {
                if (imageFiles[i].path === window.currentImage.path) {
                    return i;
                }
            }
            return -1;
        }
        
        // 更新导航按钮状态
        function updateNavigationButtons() {
            const imageFiles = getImageFilesInCurrentDirectory();
            const currentIndex = getCurrentImageIndex(imageFiles);
            
            const prevBtn = $('#prevImageBtn');
            const nextBtn = $('#nextImageBtn');
            
            // 默认隐藏按钮
            prevBtn.addClass('d-none');
            nextBtn.addClass('d-none');
            
            // 如果有多个图片文件，则显示导航按钮
            if (imageFiles.length > 1) {
                // 显示上一张按钮（如果不是第一张）
                if (currentIndex > 0) {
                    prevBtn.removeClass('d-none');
                }
                
                // 显示下一张按钮（如果不是最后一张）
                if (currentIndex < imageFiles.length - 1) {
                    nextBtn.removeClass('d-none');
                }
            }
        }
        
        // 切换到上一张图片
        function showPreviousImage() {
            const imageFiles = getImageFilesInCurrentDirectory();
            const currentIndex = getCurrentImageIndex(imageFiles);
            
            if (currentIndex > 0) {
                const prevImage = imageFiles[currentIndex - 1];
                window.currentImage = prevImage;
                
                // 更新模态框标题
                $('#imagePreviewTitle').text(`图片预览 - ${prevImage.name}`);
                
                // 重置状态并加载新图片
                resetImagePreviewState();
                loadImagePreview(prevImage.path, prevImage.name);
                
                // 更新导航按钮状态
                updateNavigationButtons();
            }
        }
        
        // 切换到下一张图片
        function showNextImage() {
            const imageFiles = getImageFilesInCurrentDirectory();
            const currentIndex = getCurrentImageIndex(imageFiles);
            
            if (currentIndex >= 0 && currentIndex < imageFiles.length - 1) {
                const nextImage = imageFiles[currentIndex + 1];
                window.currentImage = nextImage;
                
                // 更新模态框标题
                $('#imagePreviewTitle').text(`图片预览 - ${nextImage.name}`);
                
                // 重置状态并加载新图片
                resetImagePreviewState();
                loadImagePreview(nextImage.path, nextImage.name);
                
                // 更新导航按钮状态
                updateNavigationButtons();
            }
        }
        
        // 页面加载完成后初始化
        $(document).ready(function() {
            console.log('DOM 内容加载完成，开始初始化...');
            
            // 绑定导航按钮事件
            $('#prevImageBtn').on('click', showPreviousImage);
            $('#nextImageBtn').on('click', showNextImage);
            
            // 绑定键盘事件（左右箭头键）
            $(document).on('keydown', function(e) {
                // 只有当图片预览模态框显示时才处理键盘事件
                if ($('#imagePreviewModal').hasClass('show')) {
                    if (e.keyCode === 37) { // 左箭头键
                        e.preventDefault();
                        showPreviousImage();
                    } else if (e.keyCode === 39) { // 右箭头键
                        e.preventDefault();
                        showNextImage();
                    }
                }
            });
            
            // 等待短暂时间，确保所有元素都已渲染
            setTimeout(function() {
                try {
                    initializeView();
                    // 初始化缩略图加载
                    handleThumbnailLoad();
                    // 初始化懒加载
                    initLazyLoading();
                    
                    console.log('所有初始化完成');
                } catch (e) {
                    console.error('初始化过程发生错误:', e);
                }
            }, 100);
        });
        
        // 全局错误处理
        $(window).on('error', function(event) {
            if (event.message && event.message.includes('switchView')) {
                console.error('检测到 switchView 相关错误:', event.message);
                console.error('错误详情:', event);
            }
        });
        
        // 删除确认函数
        function confirmDelete(button) {
            const filePath = $(button).attr('data-file-path');
            const fileName = $(button).attr('data-file-name');
            const isDirectory = $(button).attr('data-is-directory') === 'true';
            
            const itemType = isDirectory ? '目录' : '文件';
            const message = `确定要删除${itemType} "${fileName}" 吗？`;
            
            $('#deleteMessage').text(message);
            $('#deleteFilePath').val(filePath);
            
            // Bootstrap 4 语法
            $('#deleteConfirmModal').modal('show');
        }
        
        // 暴露到全局作用域
        window.confirmDelete = confirmDelete;
        
        // 新建目录函数
        function showCreateDirectoryModal() {
            try {
                // Bootstrap 4 语法
                $('#createDirectoryModal').modal('show');
                
                // 清空输入框
                const inputField = $('#directoryName');
                if (inputField.length > 0) {
                    inputField.val('');
                    // 延迟聚焦，确保模态框完全显示
                    setTimeout(() => {
                        inputField.focus();
                    }, 300);
                }
            } catch (e) {
                console.error('显示新建目录模态框失败:', e);
                // 降级处理
                const dirName = prompt('请输入目录名称:');
                if (dirName) {
                    createDirectory(dirName);
                }
            }
        }
        
        // 暴露到全局作用域
        window.showCreateDirectoryModal = showCreateDirectoryModal;
        
        // 创建目录函数
        function createDirectory(dirName) {
            if (!dirName || dirName.trim() === '') {
                alert('目录名称不能为空');
                return;
            }
            
            // 获取当前路径
            const currentPath = '[[${currentPath}]]';
            
            // 发送创建目录请求
            fetch('/file/api/create-directory', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `parentPath=${encodeURIComponent(currentPath)}&dirName=${encodeURIComponent(dirName.trim())}`
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('创建目录失败');
                }
            })
            .then(message => {
                alert('目录创建成功');
                // 刷新页面
                window.location.reload();
            })
            .catch(error => {
                console.error('创建目录失败:', error);
                alert('创建目录失败: ' + error.message);
            });
        }
        
        // 格式化文件大小函数
        function formatFileSize(bytes) {
            if (bytes < 1024) {
                return bytes + ' B';
            } else if (bytes < 1024 * 1024) {
                return (bytes / 1024).toFixed(1) + ' KB';
            } else if (bytes < 1024 * 1024 * 1024) {
                return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
            } else {
                return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
            }
        }
        
        // 显示重命名模态框
        function showRenameModal(button) {
            const filePath = $(button).attr('data-file-path');
            const fileName = $(button).attr('data-file-name');
            
            if (!filePath || !fileName) {
                alert('缺少必要的文件信息');
                return;
            }
            
            // 设置模态框中的值
            $('#oldPath').val(filePath);
            $('#newName').val(fileName);
            
            // 显示模态框
            $('#renameModal').modal('show');
        }
        
        // 暴露到全局作用域
        window.showRenameModal = showRenameModal;
        
        // 处理重命名提交
        function handleRenameSubmit() {
            const oldPath = $('#oldPath').val();
            const newName = $('#newName').val().trim();
            
            if (!oldPath) {
                alert('原文件路径不能为空');
                return;
            }
            
            if (!newName) {
                alert('新名称不能为空');
                return;
            }
            
            // 发送重命名请求
            fetch('/file/api/rename', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `oldPath=${encodeURIComponent(oldPath)}&newName=${encodeURIComponent(newName)}`
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('重命名失败');
                }
            })
            .then(message => {
                alert(message);
                // 关闭模态框
                $('#renameModal').modal('hide');
                // 刷新页面
                window.location.reload();
            })
            .catch(error => {
                console.error('重命名失败:', error);
                alert('重命名失败: ' + error.message);
            });
        }
        
        // 绑定重命名提交事件
        $('#renameSubmitBtn').on('click', handleRenameSubmit);
        
        // 自动隐藏成功/错误消息
        setTimeout(function() {
            $('.alert').each(function() {
                // Bootstrap 4 语法
                setTimeout(function() {
                    if ($(this).parent().length > 0) {
                        $(this).alert('close');
                    }
                }, 5000);
            });
        }, 100);
    </script>
</body>
</html>